# 请在执行docker-compose之前执行此脚本

set -e

# 检查 root 权限
if [ "$EUID" -ne 0 ]; then
  echo "请使用 root 权限运行该脚本" >&2
  exit 1
fi

dirs=(
  "/docker/xxl-job/logs"
  "/docker/mongodb/data"
  "/docker/mongodb/mongo-init-scripts"
  "/docker/mysql/data"
  "/docker/mysql/conf"
  "/docker/mysql/initdb"
  "/docker/redis/data"
  "/docker/redis/conf"
  "/docker/es/conf"
  "/docker/es/data"
  "/docker/es/plugins"
  "/docker/rocketmq/data/namesrv/logs"
  "/docker/rocketmq/data/namesrv/store"
  "/docker/rocketmq/data/broker/logs"
  "/docker/rocketmq/data/broker/store"
  "/docker/rocketmq/conf"
  "/docker/portainer/data"
  "/docker/portainer/public"
  "/docker/xiaofanshu/logs"
)

files=(
  "/docker/xxl-job/application.properties"
  "/docker/es/conf/elasticsearch.yml"
  "/docker/rocketmq/conf/broker.conf"
)

echo "开始创建目录..."
for dir in "${dirs[@]}"; do
  if [ ! -d "$dir" ]; then
    mkdir -p "$dir"
    echo "已创建目录: $dir"
  else
    echo "目录已存在: $dir"
  fi
done

echo "开始创建文件..."
for file in "${files[@]}"; do
  if [ ! -f "$file" ]; then
    touch "$file"
    echo "已创建文件: $file"
  else
    echo "文件已存在: $file"
  fi
done

echo "开始设置权限..."

for dir in "${dirs[@]}"; do
  chmod -R 777 "$dir"
done

for file in "${files[@]}"; do
  chmod 777 "$file"
done

echo "权限设置完成。"

# 复制并设置初始化文件
for src_dest in "init.sql:/docker/mysql/initdb/init.sql" \
                "init-message.js:/docker/mongodb/mongo-init-scripts/init-message.js" \
                "redis.conf:/docker/redis/conf/redis.conf" \
                "elasticsearch.yml:/docker/es/conf/elasticsearch.yml" \
                "broker.conf:/docker/rocketmq/conf/broker.conf"
do
  src="config/${src_dest%%:*}"
  dest="${src_dest#*:}"

  if [ ! -f "$src" ]; then
    echo "错误: 源文件 $src 不存在，终止执行"
    exit 1
  fi

  cp "$src" "$dest"
  chmod 777 "$dest"
  echo "$src 已复制到 $dest 并设置777权限"
done

# 设置 vm.max_map_count 参数，确保 ElasticSearch 正常运行
echo "开始设置 vm.max_map_count 参数..."

if grep -q '^vm.max_map_count' /etc/sysctl.conf; then
  sed -i 's/^vm.max_map_count=.*/vm.max_map_count=262144/' /etc/sysctl.conf
  echo "已更新 /etc/sysctl.conf 中的 vm.max_map_count"
else
  echo 'vm.max_map_count=262144' >> /etc/sysctl.conf
  echo "已追加 vm.max_map_count 到 /etc/sysctl.conf"
fi

sysctl -p

current_value=$(sysctl vm.max_map_count | awk '{print $3}')
if [ "$current_value" = "262144" ]; then
  echo "系统参数 vm.max_map_count 已成功设置为 $current_value"
else
  echo "警告：系统参数 vm.max_map_count 设置失败，当前值为 $current_value"
fi

echo "脚本执行完毕。"
